@echo off
setlocal enabledelayedexpansion

echo 开始构建 MarkEdit...

REM 检查Go环境
where go >nul 2>nul
if %errorlevel% neq 0 (
    echo 错误: 未找到Go环境，请先安装Go
    exit /b 1
)

REM 设置环境变量
set CGO_ENABLED=0
if "%GOOS%"=="" set GOOS=windows
if "%GOARCH%"=="" set GOARCH=amd64

REM 创建构建目录
set BUILD_DIR=build
if not exist %BUILD_DIR% mkdir %BUILD_DIR%

echo 正在下载依赖...
go mod download
if %errorlevel% neq 0 (
    echo 错误: 依赖下载失败
    exit /b 1
)

go mod verify
if %errorlevel% neq 0 (
    echo 错误: 依赖验证失败
    exit /b 1
)

echo 正在运行测试...
go test ./...
if %errorlevel% neq 0 (
    echo 警告: 测试失败，但继续构建
)

echo 正在构建应用...
go build -a -installsuffix cgo -ldflags="-w -s" -o %BUILD_DIR%/markedit.exe ./cmd/server
if %errorlevel% neq 0 (
    echo 错误: 构建失败
    exit /b 1
)

echo 正在复制资源文件...
xcopy /E /I /Y config %BUILD_DIR%\config\
xcopy /E /I /Y web %BUILD_DIR%\web\

echo 构建完成！
echo 可执行文件: %BUILD_DIR%\markedit.exe
echo 配置文件: %BUILD_DIR%\config\
echo 静态文件: %BUILD_DIR%\web\

REM 创建启动脚本
echo @echo off > %BUILD_DIR%\start.bat
echo cd /d "%%~dp0" >> %BUILD_DIR%\start.bat
echo markedit.exe >> %BUILD_DIR%\start.bat
echo pause >> %BUILD_DIR%\start.bat

echo 启动脚本: %BUILD_DIR%\start.bat
echo.
echo 使用方法:
echo   cd %BUILD_DIR%
echo   start.bat

pause